import { spawn } from 'child_process';
import pino from 'pino';
import config from '../config.js';
import PushApi from './PushApi.js';

export default class BiliupApi {

    static async upload(mp4path, title) {
        const logger = pino({ transport: { target: 'pino-pretty' } });
        return new Promise((res, rej) => {
            const cmd = [
                '-u', config.up.cookiepath,
                'upload', mp4path,
                '--title', title,
                '--tag', config.up.tags,
                '--line', 'ws',
                '--limit', '3',
                '--cover', config.up.coverpath
            ];
            let p = spawn('biliup', cmd, {windowsHide:true});
            p.stdout.on('data', (data) => {
                logger.info('stdout: ' + data.toString());
            });
            p.stderr.on('data', (data) => {
                logger.info('stderr: ' + data.toString());
            });
            p.on('close', (code) => {
                logger.info(`上传到B站结束,biliup退出:code:${code}`);
                res();
            });
            p.on('error', (error) => {
                rej(error);
            });
        }).catch(ex => {
            logger.error(ex);
            PushApi.push('上传到B站异常', ex.toString());
        });
    }
}